<template>
	<eui-page-frame topHeight="260">
		<template #top>
			<view class="content-img">
				<eui-navbar ref="RdsNavBar" title="装车运输单" color="#000000" backgroundColor="#FFFFFF"
					:storeName="sUserStoreName" :storeId="sUserStore" :option="nbOption" @menuFunc="onClickMenuFunc"
					@onClickStore="clickStore">
				</eui-navbar>
				<view class="top-view">
					<eui-search-bar ref="RdsSearchBar" leftIcon="icon-sousuo" v-model="searchText"
						placeholder="请输入商品条码、编码" @confirm="searchConfirm" @leftIconClick="scanCode" radius="30"
						showFilter="true">
						<template v-slot:searchFields>
							<view class="search-fields">
								<view class="center">
									<eui-card-input class="search-field" v-model="formData.c_id" title="单据号"
										placeholder="请输入单据号" type="text" />
									<eui-card-input class="search-field" v-model="formData.c_src_id" title="来源单号"
										placeholder="请输入来源单据号" type="text" />
									<eui-card-input class="search-field" v-model="formData.c_status" title="费用状态"
										type="radio" :range="getDictSelectList('PO类单据状态')" />
									<eui-card-input class="search-field" v-model="formData.c_mk_dt_s" title="配送开始日期"
										placeholder="请选择开始日期" type="date" :displayable="false" rightIconType="clear"
										@iconClick="clear" singleTag="c_mk_dt_s" />
									<eui-card-input class="search-field" v-model="formData.c_mk_dt_e" title="配送结束日期"
										placeholder="请选择结束日期" type="date" :displayable="false" rightIconType="clear"
										@iconClick="clear" singleTag="c_mk_dt_e" />

								</view>
								<view class="bottom flex-1 flex">
									<eui-button type="max2" title="重置" singleTag="reset"
										@buttonClick="confirm"></eui-button>
									<eui-button type="max" title="确认" singleTag="fix"
										@buttonClick="confirm"></eui-button>
								</view>
							</view>
						</template>
					</eui-search-bar>
				</view>
			</view>
		</template>
		<!-- <eui-page-content> -->
		<view class="footer-view">
			<eui-virtual-list @onRefresh="getData" @lower="templateLower" refresher="true" isBottom="true"
				:origList="dataList" :options="dataOptions" type="list" @itemClick="onClickGoToDetail">
				<template v-slot:bottom="scope">
					<view v-if="scope.c_status != '8' || scope.c_approve_status != '3'">
						<eui-button type="min" title="详情" :modelValue="scope"
							v-if="['3', '8', '9'].includes(scope.c_status)" @buttonClick="detailClick" />
						<eui-button type="min2" v-if="scope.c_status == '0'" title="编辑" :modelValue="scope"
							style="margin-left: 20rpx;" @buttonClick="editClick" />
						<eui-button type="min" v-if="scope.c_status == '0'" title="审核" :modelValue="scope"
							style="margin-left: 20rpx;" @buttonClick="auditClick" />
					</view>
				</template>
			</eui-virtual-list>
		</view>
		<!-- </eui-page-content> -->
	</eui-page-frame>
</template>

<script setup type="ts">
	import { ref, reactive, onMounted } from 'vue';
	import {useMainStore} from "@/store/modules/store";
	import {useLoginStore} from "@/store/modules/useLoginStore";
	import { validateStores } from '@/hooks/useValidateMethod';
	import dateRangUtil from '../../../common/dateRangUtil';
	import { getRelatedName, getDictName,getDictSelectList, getDictSelect,getFreshLocationName } from '../components/RelatedName.js';
	import Enjoy from "@/common/enjoy";
	import {onLoad} from "@dcloudio/uni-app";
	import { init } from '@/hooks/init';
	import useService from '@/hooks/useService';
	import dayjs from 'dayjs';
	const service = useService({ prefix: "scApi" });
	
	const mainStore = useMainStore();
	const LoginStore = useLoginStore();
	const RdsNavBar = ref(null);
	const RdsSearchBar = ref(null);
	const { loginInfo } = mainStore;
	const searchText = ref('');
	const sUserStore = ref('');
	const sUserStoreName = ref('');
	const sUser = ref('');
	const listHeight = ref(300);
	const nbOption = ref({
	  items: [
	    {title: '新增', onClick: 'onClickNewCount', icon: 'plusempty'},
	  ]
	})
	const formData = ref({
	   c_mk_dt_s: (dateRangUtil.getLast1Month())[0],
	   c_mk_dt_e: (dateRangUtil.getLast1Month())[2],
	   c_id: '',
	   c_src_id: '',
	   c_status: '',
	
	})
	const dataList = ref([]);
	const CurrentPage = ref(1);  //第几页
	const PageSize = ref(10);  //每页10条
	const RowsCount = ref(0);  //总条数
	const PageCount = ref(1);  //总页数
	
	const dataOptions = ref([
		{ label:"配送中心", name:"c_dc_store_name",occupy: true },
		{ label: "费用单号", name: "c_pur_fee_id" },
		{ label: "波次", name: "c_wave" },
		{ label: "采购地", name: "c_pl_no_name" },
		{ label: "采购员", name: "c_buyer_name" },
		{ label: "目的机构", name: "c_d_store_name",occupy: true },
		{ label: "录入", name: "c_mk_userinfo",occupy: true },
		{ label: "审核", name: "c_au_userinfo",occupy: true },
	])
	
	const setDefault = () => {
		sUserStore.value = loginInfo.sUserStore;
		sUserStoreName.value = loginInfo.sUserStoreName;
		sUser.value = loginInfo.sUser;
	}
	
	onLoad(async (option) => {
	  //await init()
	  if (!loginInfo.sUserStore) {
	    RdsNavBar.value.onClickStore();
	    return;
	  }
	  if (option.c_src_id) {
	  		formData.value.c_src_id = option.c_src_id 
	  }
	  setDefault();
	  await getData();
	})
	
	const clear = (e)=>{
		switch (e) {
			case 'c_mk_dt_s':
			  formData.value.c_mk_dt_s = '';
			  break;
			case 'c_mk_dt_e':
			  formData.value.c_mk_dt_e = '';
			  break;
		}
	}
	const confirm = async(t) => {
	  let { singleTag } = t;
	  switch (singleTag) {
	    case 'reset':
	       formData.value.c_mk_dt_s = (dateRangUtil.getLast1Month())[0];
	       formData.value.c_mk_dt_e = (dateRangUtil.getLast1Month())[2];
		   formData.value.c_id = '';
		   formData.value.c_src_id = '';
		   formData.value.c_status = '';
	      break;
	    case 'fix':
	      // 关闭弹出层
	      RdsSearchBar.value.closeDrawer();
		  await getData();
	      break;
	  }
	}
	const searchConfirm = async (e) => {
	  if (!e) {
	    return;
	  }
	  searchText.value = e.value;
	  await getData();
	}
	// 新增单据
	const onClickMenuFunc = async(e) => {
	  console.log('=====onClickMenuFunc: ', e);
	  switch (e) {
	    case 'onClickNewCount':
	      setTimeout(() => {
	        RdsNavBar.value.closeDrawer();
	      },1200);
		  await onClickNewCount();
	      break;
	  }
	}
	const onClickNewCount = async(e)=> {
		//RdsNavBar.value.closeDrawer();
		const result = await validateStores(
		    { fieldName: 'c_store_id', newValue: sUserStore.value },
		    { ischecklimit: true, firstValueMode: true }
		);
		if (!['3'].includes(result.c_type)) {
		    uni.showToast({
		        title: '当前机构不允许新建装车运输单,请切换至配送中心!',
		        icon: 'none',
		        duration: 2000,
		    });
		    return;
		}
		uni.navigateTo({
			url: './edit?storeId=' + sUserStore.value
		});
	}
	// 选择框点击事件
	const clickStore = () => {
	  let parms = Enjoy.GetDialogParms();
	  parms.CallBack = SelectionStoreChanged;
	  parms.SelectionType = "机构选择";
	  parms.SelectedItems = sUserStore.value;
	  Enjoy.OpenDialog(parms)
	}
	const SelectionStoreChanged = async (event) => {
	  if (event.SelectionType == '机构选择') {
	    // 更新机构信息
	    sUserStoreName.value = event.BackParms.Value;
	    sUserStore.value = event.BackParms.Key;
	  }
	  // 按新条件获取数据
	  await getData();
	}
	// 上拉加载更多
	const templateLower = async() =>{
		if (CurrentPage.value < PageCount.value) {
			CurrentPage.value = CurrentPage.value + 1;
			await getData(true);
		}
	}
	const templateUpper = async()=>{
		if (CurrentPage.value < PageCount.value) {
			CurrentPage.value = CurrentPage.value + 1;
			await getData(true);
		}
	}
	const getData = async(e) => {
		if (!e) {
			CurrentPage.value = 1;
		}
		const req = {
			IsNotPage: false,
			CurrentPage: CurrentPage.value,
			PageSize: PageSize.value,
			UserNo: sUser.value,
			WhereList: [
				{ c_col: "c_dc_store_id", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
				formData.value.c_mk_dt_s ? { c_col: "c_mk_dt", c_oper: "大于等于", c_value: formData.value.c_mk_dt_s, c_logic: "而且", c_col_dtype: "System.DateTime" } : {},
				formData.value.c_mk_dt_e ? { c_col: "c_mk_dt", c_oper: "小于等于", c_value: formData.value.c_mk_dt_e, c_logic: "而且", c_col_dtype: "System.DateTime" } : {},
				formData.value.c_status ? { c_col: "c_status", c_oper: "等于", c_value: formData.value.c_status, c_logic: "而且" } : {},
				formData.value.c_id ? { c_col: "c_id", c_oper: "等于", c_value: formData.value.c_id, c_logic: "而且" } : {},
				formData.value.c_src_id ? { c_col: "c_src_id", c_oper: "等于", c_value: formData.value.c_src_id, c_logic: "而且" } : {},
			]
		}
		if (searchText.value) {
			req.WhereList.push({
				c_col: "c_gcode",
				c_oper: "等于",
				c_value: searchText.value,
				c_logic: "而且",
			});
		}
		uni.showLoading({ title: "正在加载...", mask: true })
		const result = await service.request('装车运输单', 'EnjoyQueryList', req,'');
		uni.hideLoading(); 
		
		CurrentPage.value = result.CurrentPage; //第几页
		PageSize.value = result.PageSize; //每页10条
		RowsCount.value = result.RowsCount; //总条数
		PageCount.value = result.PageCount; //总页数
		const _data = result.ReturnObject.map(x=>{
			return {
				...x,
				c_dc_store_name:`[${x.c_dc_store_id}]${getRelatedName('rdsStores', x.c_dc_store_id)||''}`,
				c_pl_name:getFreshLocationName(x.c_pl_no),
				c_buyer_name:x.c_buyer_no?`[${x.c_buyer_no}]${getRelatedName('rdsUsers', x.c_buyer_no)||''}`:'',
				c_d_store_name:x.c_d_store_id?`[${x.c_d_store_id}]${getRelatedName('rdsStores', x.c_d_store_id)||''}`:'',
				c_mk_userinfo:`[${x.c_mk_userno}]${getRelatedName('rdsUsers', x.c_mk_userno)||''}` + '   '+ dayjs(x.c_mk_dt).format('YYYY-MM-DD HH:mm:ss'),
				c_au_userinfo:(x.c_au_userno ? `[${x.c_au_userno}]${getRelatedName('rdsUsers', x.c_au_userno)||''}`:'') + '  '+ (x.c_au_dt ? dayjs(x.c_au_dt).format('YYYY-MM-DD HH:mm:ss'):'')
			} 
		})
		if (result.CurrentPage == 1) {
			dataList.value = _data;
		} else {
			dataList.value = dataList.value.concat(_data);
		}
	}
	const onClickGoToDetail = (e) => {
		uni.navigateTo({
			url: './edit?c_id=' + e.item.c_id + '&storeId=' + sUserStore.value
		});
	}
	const detailClick = (item)=>{
		uni.navigateTo({
					   url: './edit?c_id=' + item.modelValue.c_id + '&storeId=' + item.modelValue.c_dc_store_id
					});
	}
	const auditClick = (item)=>{
		 const req = {
		                BillId: item.modelValue.c_id,
		                UserNo: loginInfo.sUser
		            }
		if(item.modelValue.c_status=="0"){
			 uni.showModal({
				title: ' 提示',
				content: '请确认，审核单据[' + req.BillId + ']?',
				showCancel: true,
				success: async (res) => {
					if (res.confirm) {
						uni.showLoading({ title: "正在审核...", mask: true });
						const result = await service.request('装车运输单', 'EnjoyBillAudit', req,'5H1');
						uni.hideLoading(); 
						uni.showToast({
							duration: 3500,
							icon: 'none',
							title: ' 审核成功！'
						});
						setTimeout(async () => {
							await getData();
						}, 1000);
					}
				}
			});
		}
	}
	const editClick = (item)=>{
		 uni.navigateTo({
			   url: './edit?c_id=' + item.modelValue.c_id + '&storeId=' + item.modelValue.c_dc_store_id
			});
	}
</script>

<style lang="scss" scoped>
	@import '../../../main.scss';

	.content {
		display: flex;
		flex: 1;
		flex-direction: column;
		background-color: #F2F2F2;
		padding: 0px !important
	}

	.content-img {
		background-color: #FFFFFF;
		background-size: 100% 176rpx;
		background-repeat: no-repeat;
		width: 100%;
	}

	.navigation {
		flex: 0 0 auto;
		margin-bottom: 5px;
	}

	.top-view {
		width: 100%;
		height: 88rpx;
		background: #FFFFFF;
	}

	.footer-view {
		height: 100%;
		background: $uni-bg-color;
	}

	.search-fields {
		width: 100%;
		background: #FFFFFF;
		position: relative;

		.bottom {
			background: #ffffff;
			border-top: 1rpx solid $uni-line-color;
			display: flex;
			justify-content: center;
			padding: 20rpx;
		}
	}

	::v-deep .white-main {
		left: 0;
		right: 0;
	}
</style>